import Vue from 'vue'
import router from './router'
import store from './store'
import {
  otherRoutersMap,
} from '@/config/router.config'
import NProgress from 'nprogress'
import '@/components/NProgress/nprogress.less'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
NProgress.configure({ showSpinner: false })
const whiteList = ['loginCode','errorCode'] 
const defaultRoutePath = '/workplace'
router.beforeEach(async (to, from, next) => {
  NProgress.start() 
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`));
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (to.path === '/login') {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      let sign = store.getters.sign;
      if (sign) {
        next()
      } else {
        // await store.dispatch('getSysTaskConfigEnableList');
        let accessRoutes = await store.dispatch('generateRoutes');
        // await store.dispatch('allGetCanmpanyDetail');
        // await store.dispatch('allGetSttleEnterpriseIsOpenAccount');
        // await store.dispatch('allEnterpriseIdQueryEnterpriseSet',store.getters.userInfo.relationId);
        accessRoutes = otherRoutersMap.concat(accessRoutes)
        router.addRoutes(accessRoutes)
        let redirect = decodeURIComponent(from.query.redirect || to.path)
        if (to.path === redirect) {
          next({ ...to, replace: true })
        } else {
          next({ path: redirect })
        }
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      next(`/login`)
      NProgress.done() 
    }
  }
})
router.afterEach(() => {
  NProgress.done() 
})
